package cn.wolfcode.shop.cloud.mq;


import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@RocketMQMessageListener(
        consumerGroup = MQConstans.CREATE_ORDER_GROUP,
        topic = MQConstans.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstans.CREATE_ORDER_TAG
)
@Component
public class OrderCreateMQListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("创建订单的消费者");

        //接受传过来的参数

        Long userId = orderMessage.getUserId();
        String uuid = orderMessage.getUuid();
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("seckillId",orderMessage.getSeckillId());
        try {

            String orderNo = orderInfoService.seckill(userId, orderMessage.getSeckillId());
            map.put("data", orderNo);
            map.put("code", 200);
            //发送成功消息
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_SUCCESS_DEST, map);
            System.out.println("订单信息创建成功");
        } catch (Exception e) {
            //订单创建失败

            // 回滚预售

            // 发布失败消息
            map.put("data", "");
            map.put("code", 500);
            rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_FAIL_DEST, map);


        }
    }
}
